package com.woniuxy.charin.controller;

import com.woniuxy.charin.util.QiNiuUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Api(tags = "文件上传")
public class UploadController {
    @ApiOperation("文件上传")
    @PostMapping("/images")
    public ResponseEntity<String> upload(@RequestPart MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空");
        }

        // 获取文件名称和扩展名
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + fileExtension;

        // 上传文件到存储
        String fileKey = QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);
        if (fileKey == null || fileKey.isEmpty()) {
            return ResponseEntity.status(500).body("文件上传失败");
        }

        // 拼接七牛云的完整 URL
        String cdnHost = "http://sp6zi9loh.hn-bkt.clouddn.com/"; // 替换为你的 CDN 域名
        String fullUrl = cdnHost + fileKey;

        return ResponseEntity.ok(fullUrl);
    }

    @DeleteMapping("/delete")
    public ResponseEntity<?> deleteFile(@RequestParam String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return ResponseEntity.badRequest().body("File name is required");
        }

        boolean isDeleted = QiNiuUploadUtils.deleteFile(fileName);
        if (isDeleted) {
            return ResponseEntity.ok("File deleted successfully");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to delete file");
        }
    }

    @ApiOperation("更改图片")
    @PutMapping("/update")
    public ResponseEntity<String> update(@RequestPart MultipartFile file, @RequestParam String oldFileName) throws IOException {
        if (file.isEmpty() || oldFileName == null || oldFileName.isEmpty()) {
            return ResponseEntity.badRequest().body("文件或旧文件名不能为空");
        }

        // 获取新文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = uuid + fileExtension;

        // 调用工具类删除旧文件并上传新文件
        QiNiuUploadUtils.updateFile(file.getBytes(), oldFileName);

        // 返回新的文件路径
        String pathUrl = "http://sp6zi9loh.hn-bkt.clouddn.com/" + newFileName;
        return ResponseEntity.ok(pathUrl);
    }
}
